package com.vm.fragment;

import java.io.File;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.vm.activity.DetailActivity;
import com.vm.activity.ImageShower;
import com.vm.broadcast.AppInstallReceiver;
import com.vm.commons.CurrentSetting;
import com.vm.commons.CurrentUser;
import com.vm.commons.ProgressUtil;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.vm.db.DownInfoDao;
import com.vm.db.LocalUserInfoDao;
import com.vm.db.OperationDao;
import com.vm.model.DownInfo;
import com.vm.model.Scene;
import com.vm.model.Soft;
import com.vm.myview.NotificationView;
import com.vm.utils.ApkUtils;
import com.vm.utils.ConnectManager;
import com.vm.utils.DownloadThread;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyVolley;
import com.vm.utils.ThreadManager;
import com.wwtscapp.apk.R;

@SuppressLint({ "InflateParams", "ShowToast" })
public class IntroduceFragment extends BaseFragment {

	protected static final String TAG = "IntroduceFragment";
	private View view;
	RequestQueue mQueue;
	Soft soft;
	TextView tv_software_content;

	Button btn_download;
	ProgressBar progressBar1;
	int addRecord;
	private int fileSize = 0;
	private int nowProgressValue = 0;
	private DownloadThread downThread;
	private TextView progressText;
	String currentId;
	DownInfoDao dao;
	DownInfo apkInfo;
	Integer isNow;

	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryGameFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.software_details, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		isPrepared = true;
		lazyLoad();

	}

	@SuppressLint("HandlerLeak")
	private Handler downloadHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 10:
				if (progressText.getText().toString().equals("下载")) {
					btn_download.setEnabled(false);

					progressText.setText("暂停");
					// 下载APK
					btn_download.setVisibility(View.GONE);
					//
					progressBar1.setVisibility(View.VISIBLE);

					Message msg1 = new Message();
					// msg.arg1 = currentId;
					msg1.what = 100;
					// 下载地址
					// msg.obj = VMConst.DOWN_URL + currentId +
					// "&userId="
					// + CurrentUser.USERID;
					msg1.obj = soft;
					downThread = getDownloadThread();

					ProgressUtil.hashMap.put(soft.getId(), nowProgressValue);
					do {
						downHandler = downThread.getDownHandler();
					} while (null == downHandler);
					downHandler.sendMessage(msg1);

					progressBar1.setEnabled(true);

				} else if (progressText.getText().toString().equals("继续")) {
					progressBar1.setEnabled(false);
					// btn_download.setVisibility(View.GONE);
					// progressBar1.setVisibility(View.VISIBLE);
					if (downThread != null) {
						if (downThread.isPause) {
							downThread.isPause = false;
							downThread.restart();
							fileSize = apkInfo.getApkLength();
							btn_download.setVisibility(View.GONE);
							progressBar1.setVisibility(View.VISIBLE);
							progressText.setText("稍等");
							progressText.setTextColor(Color.WHITE);
							progressBar1.setMax(fileSize);
							new Thread() {
								@Override
								public void run() {
									while (true) {
										progressBar1
												.setProgress(nowProgressValue);
									}
								}
							}.start();
						}
					} else {
						fileSize = apkInfo.getApkLength();
						btn_download.setVisibility(View.GONE);

						progressBar1.setVisibility(View.VISIBLE);
						progressText.setText("稍等");
						progressText.setTextColor(Color.WHITE);

						progressBar1.setMax(fileSize);
						new Thread() {
							@Override
							public void run() {
								while (true) {
									progressBar1.setProgress(nowProgressValue);
								}
							}
						}.start();
						Message msg1 = new Message();
						msg1.what = 100;
						msg1.obj = soft;

						downThread = getDownloadThread();
						dao.start(soft.getId());

						ProgressUtil.hashMap
								.put(soft.getId(), nowProgressValue);
						if (downHandler == null) {
							downHandler = downThread.getDownHandler();
						}
						downHandler.sendMessage(msg1);
					}
					// progressText.setText("暂停");
					progressBar1.setEnabled(true);

				}

				break;
			}
		}
	};

	/**
	 * 初始化控件
	 */
	private void init() {
		dao = new DownInfoDao(getActivity());
		tv_software_content = (TextView) view
				.findViewById(R.id.tv_introduce_content);
		btn_download = (Button) view.findViewById(R.id.btn_soft_download);

		// btn_download_finish = (Button) view
		// .findViewById(R.id.btn_soft_download);
		progressBar1 = (ProgressBar) view.findViewById(R.id.progressBar1);

		progressText = (TextView) view.findViewById(R.id.progressText);

	}

	public void initData() {
		soft = (Soft) getArguments().get("soft");
		addRecord = getArguments().getInt("addRecord");
		currentId = soft.getId();
		// final String softId = getActivity().getIntent()
		// .getStringExtra("softId");
		isNow = getActivity().getIntent().getIntExtra("isNow", 0);
		// currentId = softId;
		// Log.i("currentId", currentId);

		// init();

		/**
		 * 查询当前APK是否正在下载中,如果存在,下载按钮显示继续下载
		 */

		tv_software_content.setText(soft.getIntro());

		if (soft.getSceneList() != null) {
			if (soft.getSceneList().size() > 0) {
				LinearLayout layout = (LinearLayout) view
						.findViewById(R.id.l_layout_scene);
				layout.removeAllViews();
				// ImageView iv1 =
				// (ImageView)findViewById(R.id.iv_scene1);
				for (int i = 0; i < soft.getSceneList().size(); i++) {

					final Scene scene = soft.getSceneList().get(i);
					ImageView imageView = new ImageView(getActivity());
					imageView.setId(i);

					int dimens = 120;
					float density = getResources().getDisplayMetrics().density;
					int finalDimens = (int) (dimens * density);

					LinearLayout.LayoutParams imgvwDimens = new LinearLayout.LayoutParams(
							finalDimens, (int) (finalDimens * 1.5));
					imageView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent = new Intent(getActivity(),
									ImageShower.class);
							intent.putExtra("soft", soft);
							startActivity(intent);
						}
					});
					imageView.setLayoutParams(imgvwDimens);

					ImageLoader.getInstance().displayImage(
							VMConst.URL + scene.getImageUrl(), imageView,
							MyDisplayImageOptions.getInstance());

					layout.addView(imageView);

				}

			}
		}

		// 下载按钮
		btn_download.setTag(soft.getId());
		btn_download.setOnClickListener(downClickListener);
		progressBar1.setOnClickListener(progressListener);

		boolean isInstalled = ApkUtils.isAppInstalled(soft.getPackageName(),
				getActivity());
		// 判断APK是否有安装
		if (isInstalled) {
			progressText.setText("已安装");
		} else {

			File apkfile = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/vmclient/" + soft.getName() + ".apk");
			if (apkfile.exists()) {

				// 判断APK在机器的状态,正在下载,已下载,已安装
				dao = new DownInfoDao(getActivity());
				apkInfo = dao.query(currentId);
				if (apkInfo != null) {

					if (apkInfo.getCompleted() == 1) {

						progressText.setText("安装");

					} else {
						downThread = ThreadManager.getDownloadThread2(
								getActivity(), soft.getId(), mainHandler);

						if (downThread.isPause) {
							progressText.setText("继续");
						} else {
							fileSize = apkInfo.getApkLength();
							btn_download.setVisibility(View.GONE);

							progressBar1.setVisibility(View.VISIBLE);
							progressText.setText("稍等");
							progressText.setTextColor(Color.WHITE);

							progressBar1.setMax(fileSize);
							new Thread() {
								@Override
								public void run() {
									while (true) {
										progressBar1
												.setProgress(nowProgressValue);
									}
								}
							}.start();
						}
					}
				}
			}

		}
	}

	Runnable initData = new Runnable() {

		@SuppressLint("HandlerLeak")
		@Override
		public void run() {
			// TODO Auto-generated method stub
			soft = (Soft) getArguments().get("soft");
			addRecord = getArguments().getInt("addRecord");
			currentId = soft.getId();
			// final String softId = getActivity().getIntent()
			// .getStringExtra("softId");
			isNow = getActivity().getIntent().getIntExtra("isNow", 0);
			// currentId = softId;
			// Log.i("currentId", currentId);

			// init();

			/**
			 * 查询当前APK是否正在下载中,如果存在,下载按钮显示继续下载
			 */

			tv_software_content.setText(soft.getIntro());

			if (soft.getSceneList() != null) {
				if (soft.getSceneList().size() > 0) {
					LinearLayout layout = (LinearLayout) view
							.findViewById(R.id.l_layout_scene);
					layout.removeAllViews();
					// ImageView iv1 =
					// (ImageView)findViewById(R.id.iv_scene1);
					for (int i = 0; i < soft.getSceneList().size(); i++) {

						final Scene scene = soft.getSceneList().get(i);
						ImageView imageView = new ImageView(getActivity());
						imageView.setId(i);

						int dimens = 120;
						float density = getResources().getDisplayMetrics().density;
						int finalDimens = (int) (dimens * density);

						LinearLayout.LayoutParams imgvwDimens = new LinearLayout.LayoutParams(
								finalDimens, (int) (finalDimens * 1.5));
						imageView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								Intent intent = new Intent(getActivity(),
										ImageShower.class);
								intent.putExtra("soft", soft);
								startActivity(intent);
							}
						});
						imageView.setLayoutParams(imgvwDimens);

						ImageLoader.getInstance().displayImage(
								VMConst.URL + scene.getImageUrl(), imageView,
								MyDisplayImageOptions.getInstance());

						layout.addView(imageView);

					}

				}
			}

			// 下载按钮
			btn_download.setTag(soft.getId());
			btn_download.setOnClickListener(downClickListener);
			progressBar1.setOnClickListener(progressListener);

			boolean isInstalled = ApkUtils.isAppInstalled(
					soft.getPackageName(), getActivity());
			// 判断APK是否有安装
			if (isInstalled) {
				progressText.setText("已安装");
			} else {

				File apkfile = new File(Environment
						.getExternalStorageDirectory().getPath()
						+ "/vmclient/"
						+ soft.getName() + ".apk");
				if (apkfile.exists()) {

					// 判断APK在机器的状态,正在下载,已下载,已安装
					dao = new DownInfoDao(getActivity());
					apkInfo = dao.query(currentId);
					if (apkInfo != null) {

						if (apkInfo.getCompleted() == 1) {

							progressText.setText("安装");

						} else {
							downThread = ThreadManager.getDownloadThread2(
									getActivity(), soft.getId(), mainHandler);

							if (downThread.isPause) {
								progressText.setText("继续");
							} else {
								fileSize = apkInfo.getApkLength();
								btn_download.setVisibility(View.GONE);

								progressBar1.setVisibility(View.VISIBLE);
								progressText.setText("稍等");
								progressText.setTextColor(Color.WHITE);

								progressBar1.setMax(fileSize);
								new Thread() {
									@Override
									public void run() {
										while (true) {
											progressBar1
													.setProgress(nowProgressValue);
										}
									}
								}.start();
							}
						}
					}
				}

			}
		}
	};

	@SuppressLint({ "ShowToast", "HandlerLeak" })
	private Handler mainHandler = new Handler() {
		@SuppressLint("ShowToast")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 100:
				progressText.setText("已安装");
				if (CurrentSetting.autodelete == 1) {
					File apkfile = new File(Environment
							.getExternalStorageDirectory().getPath()
							+ "/vmclient/" + soft.getName() + ".apk");
					if (apkfile.exists()) {
						apkfile.delete();
					}
				}
				addRecord();
				if (addRecord == 1) {
					addInteger();
				}

				break;
			case 500:
				if (nowProgressValue <= fileSize) {

					if (progressText.getText().equals("打开")) {
						progressText.setText("打开");

						Toast toast = Toast
								.makeText(getActivity(), "下载完成", 500);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					} else {
						fileSize = msg.arg1;
						progressBar1.setMax(fileSize);
						new Thread() {
							@Override
							public void run() {
								while (true) {
									progressBar1.setProgress(nowProgressValue);
								}
							}
						}.start();
					}
				} else {
					Toast toast = Toast.makeText(getActivity(), "当前附件已下载", 500);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
				}
				break;
			case 600:
				nowProgressValue = msg.arg1;
				if (nowProgressValue <= fileSize) {
					progressText.setTextColor(Color.WHITE);
					// System.out.println("<<<<<<" + fileSize + "<<<"
					// + nowProgressValue);
					double aa = ((double) nowProgressValue / (double) fileSize);
					// System.out.println("<<<<<<<<<"
					// + (Math.round(aa * 100) / 100.0));
					if (!progressText.getText().toString().equals("继续")) {
						progressText.setText((int) (aa * 100) + "%");
					}

				} else {

				}

				break;
			case 700:
				progressText.setText("下载");
				progressText.setTextColor(Color.WHITE);
				Toast toast = Toast
						.makeText(getActivity(), "网络异常或当前附件不存在", 500);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				break;
			case 800:
				Toast toast1 = Toast.makeText(getActivity(), "URL异常，请联系管理员",
						500);
				toast1.setGravity(Gravity.CENTER, 0, 0);
				toast1.show();
				break;

			case 900:
				Toast toast2 = Toast.makeText(getActivity(), "暂停下载", 500);
				toast2.setGravity(Gravity.CENTER, 0, 0);
				toast2.show();
				break;
			case 1000:
				Toast toast3 = Toast.makeText(getActivity(), "下载完成", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();

				progressText.setText("安装");

				if (progressText.getText().toString().equals("已安装")) {
					// 不做任何操作
				} else if (progressText.getText().toString().equals("安装")) {
					// 执行安装

					progressText.setText("安装");
					dao = new DownInfoDao(getActivity());
					dao.complete(currentId);
					File apkfile = new File(StringUtil.getSdApkUrl(soft
							.getName()));
					if (!apkfile.exists()) {
						return;
					}
					if (CurrentSetting.autoinstall == 1) {
						progressText.setText("正在安装");
						Intent i = new Intent(Intent.ACTION_VIEW);
						i.setDataAndType(
								Uri.parse("file://" + apkfile.toString()),
								"application/vnd.android.package-archive");
						AppInstallReceiver.mainHandler = mainHandler;
						startActivityForResult(i, 12);
						OperationDao op = new OperationDao();
						op.insert(soft.getId(), soft.getPackageName());
					}
					new NotificationView(view.getContext(), soft.getImageUrl(),
							soft.getName() + "下载完成", "点击安装", "下载完成",
							apkfile.toString());
					if (CurrentSetting.zeroflow == 1) {
						SoundPool pool = new SoundPool(10,
								AudioManager.STREAM_MUSIC, 5);
						// 载入音频流，返回在池中的id
						final int sourceid = pool.load(getActivity(),
								R.raw.down, 0);
						pool.setOnLoadCompleteListener(new OnLoadCompleteListener() {

							@Override
							public void onLoadComplete(SoundPool soundPool,
									int sampleId, int status) {
								// TODO Auto-generated method stub
								soundPool.play(sourceid, 2, 2, 0, 0, 1);
							}

						});
					}
				}
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	// 下载
	boolean isDownload = false;

	public OnClickListener progressListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (progressText.getText().toString().equals("继续")) {
				v.setEnabled(false);
				if (downThread != null) {
					if (downThread.isPause) {
						downThread.isPause = false;
						downThread.restart();
						// downThread.dao.notify();
					}
				} else {
					btn_download.setVisibility(View.GONE);
					progressBar1.setVisibility(View.VISIBLE);

					Message msg = new Message();
					msg.what = 100;
					msg.obj = soft;

					downThread = getDownloadThread();
					dao.start(soft.getId());

					ProgressUtil.hashMap.put(soft.getId(), nowProgressValue);
					if (downHandler == null) {
						downHandler = downThread.getDownHandler();
					}
					downHandler.sendMessage(msg);
				}
				progressText.setText("暂停");
				v.setEnabled(true);
			} else if (progressText.getText().toString().contains("%")) {
				v.setEnabled(false);
				downThread.isPause = true;
				dao.stop(soft.getId());
				progressText.setText("继续");
				v.setEnabled(true);
			}
		}

	};

	/**
	 * 下载按钮监听
	 */
	public OnClickListener downClickListener = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			if (progressText.getText().toString().equals("安装")) {
				v.setEnabled(false);
				// 执行安装
				Toast toast3 = Toast.makeText(getActivity()
						.getApplicationContext(), "正在安装", 500);
				toast3.setGravity(Gravity.CENTER, 0, 0);
				toast3.show();

				File apkfile = new File(StringUtil.getSdApkUrl(soft.getName()));
				if (!apkfile.exists()) {
					return;
				}
				Intent i = new Intent(Intent.ACTION_VIEW);
				i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
						"application/vnd.android.package-archive");
				view.getContext().startActivity(i);
				AppInstallReceiver.mainHandler = mainHandler;
				v.setEnabled(true);
			} else if (progressText.getText().toString().equals("暂停")) {
				v.setEnabled(false);
				downThread.isPause = true;
				progressText.setText("继续");
				dao.stop(soft.getId());
				v.setEnabled(true);
				// int a = apkInfo.getIsPause();
			}

			else {
				ConnectManager.mainHandler = downloadHandler;
				ConnectManager.isDownload(getActivity());

			}
		}

	};

	public DownloadThread getDownloadThread() {
		if (downThread == null) {
			downThread = ThreadManager.getDownloadThread(getActivity()
					.getApplicationContext().getApplicationContext(), soft
					.getId(), mainHandler);

		}
		return downThread;
	}

	private Handler downHandler = new Handler();

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void lazyLoad() {

		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				// UIHelper.showDialogForLoading(getActivity(), "正在加载...",
				// true);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {

					Thread.sleep(300);

					// initData1();
					// 在这里添加调用接口获取数据的代码
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
					Log.i(TAG, e.getMessage());
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					init();
					mHasLoadedOnce = true;

					downHandler.post(initData);
				} else {
					// 加载失败
				}
				// 关闭对话框
				// UIHelper.hideDialogForLoading();
			}
		}.execute();

	}

	public void addRecord() {
		if (CurrentUser.USERID != null) {
			RequestQueue mQueue = MyVolley.getRequestQueue();

			String url = VMConst.REQUEST_URL + "addDownloadRecord?userId="
					+ CurrentUser.USERID + "&softId=" + soft.getId()
					+ "&deviceId=" + StringUtil.DEVICEID;

			StringRequest ifGetRequest = new StringRequest(url,
					new Listener<String>() {

						@Override
						public void onResponse(String response) {
							if (response.contains("成功")) {
								System.out.println("success");
								DetailActivity detailActivity = (DetailActivity) getActivity();
								detailActivity.addRecord();
							}
						}
					}, new ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
						}
					});
			mQueue.add(ifGetRequest);
		}

	}

	public void addInteger() {
		RequestQueue mQueue = MyVolley.getRequestQueue();
		String url = VMConst.REQUEST_URL + "getDownIntergral?softId="
				+ soft.getId() + "&userId=" + CurrentUser.USERID;
		StringRequest ifGetRequest = new StringRequest(url,
				new Listener<String>() {

					@Override
					public void onResponse(String response) {
						if (response.contains("领取成功")) {
							CurrentUser.INTERGRAL += 10;
							// 更新积分
							new LocalUserInfoDao(getActivity()).update();
						}
					}

				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
					}
				});
		mQueue.add(ifGetRequest);
	}
}
